package com.c7.dan;

import com.c7.bean.NewsBean;
import com.c7.util.DBConnection;

import java.util.Date;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class NewsDao {
    DBConnection DBConn = new DBConnection();
    public List<NewsBean> getList(){
        Connection conn = DBConn.getConn();
        String sql = "select * from news";
        List<NewsBean> list = new ArrayList<NewsBean>();
        try {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(sql);
            while (rs.next()){
                NewsBean newsBean = new NewsBean();
                newsBean.setNewsId(rs.getInt("NewsId"));
                newsBean.setNewsTitle(rs.getString("NewsTitle"));
                newsBean.setNewsContent(rs.getString("NewsContent"));
                newsBean.setNewsTime(rs.getString("NewsTime"));
                newsBean.setNewsDate(rs.getString("NewsDate"));
                list.add(newsBean);
            }
        } catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加新闻
     * @param news
     * @return
     */
    public int add(NewsBean news) {
        Connection conn = DBConn.getConn();
        String sql = "insert into news value(null,?,?,?,?)";
        try {
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setString(1, news.getNewsTitle());
            pmst.setString(2, news.getNewsContent());
            pmst.setString(3, (new Date()).toString());
            pmst.setString(4, news.getNewsDate());
            return pmst.executeUpdate();
        } catch (SQLException e) {
            e.fillInStackTrace() ;
        }
        return 0;
    }

    /**
     * 更新功能
     * @param news
     * @return
     */
    public int update(NewsBean news) {
        Connection conn = DBConn.getConn();
        String sql = "update news set newsTitle=?,newsContent=?,NewsTime=?,newsDate=? where NewsId=?";
        try {
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setString(1, news.getNewsTitle());
            pmst.setString(2, news.getNewsContent());
            pmst.setString(3, (new Date()).toString());
            pmst.setString(4, news.getNewsDate());
            pmst.setInt(5, news.getNewsId());
            return pmst.executeUpdate(sql);
        } catch (SQLException ex) {
            ex.fillInStackTrace() ;
        }
        return 0;
    }
    public int delete(int newsId) {
        Connection conn = DBConn.getConn();
        try {
            String sql = "delete from news where NewsId=?";
            PreparedStatement pmst = conn.prepareStatement(sql);
            pmst.setInt(1, newsId);
            return pmst.executeUpdate(sql);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return 0;
    }
}
